package com.payscn.oss.autoconfigure;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import javax.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @author Alexander
 */
@Configuration
@ConditionalOnClass(OSSClient.class)
@EnableConfigurationProperties(OSSProperties.class)
@Slf4j
public class OSSAutoConfigure {
    private final OSSProperties properties;
    
    private OSSClient ossClient;
    
    public OSSAutoConfigure(OSSProperties ossProperties) {
        this.properties = ossProperties;
    }
    
    @PreDestroy
    public void shutdown() {
        if(null != this.ossClient) {
            log.debug("close ossClient");
            this.ossClient.shutdown();
        }
    }
    
    @Bean
    ClientConfiguration clientConfiguration() {
        ClientConfiguration config = new ClientConfiguration();
        config.setMaxConnections(properties.getMaxConnections());
        config.setConnectionTimeout(properties.getConnectionTimeout());
        config.setMaxErrorRetry(properties.getMaxErrorRetry());
        config.setSocketTimeout(properties.getSocketTimeout());
        return config;
    }
    
    @Bean
    @ConditionalOnMissingBean
    public OSSClient ossClient() {
        log.debug("create ossClient: {}", properties);
        return new OSSClient(properties.getEndpoint(), properties.getAccessKey(), properties.getAccessKeySecret(),
                clientConfiguration());
    }
}
